package cn.tedu.zx.ams.adapter.serviceimpl;


import cn.tedu.zx.ams.adapter.mapper.AdminRoleMapper;
import cn.tedu.zx.ams.adapter.mapper.RoleMapper;
import cn.tedu.zx.ams.adapter.mapper.RolePermissionMapper;
import cn.tedu.zx.ams.service.RoleService;
import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.pojo.admin.entity.Role;
import cn.tedu.zx.pojo.admin.entity.RolePermission;
import cn.tedu.zx.pojo.admin.parm.RoleAddNewParam;
import cn.tedu.zx.pojo.admin.parm.RoleUpdateParam;
import cn.tedu.zx.pojo.admin.vo.RoleListItemVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.tedu.zx.common.restful.ResponseCode.*;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public void addNew(RoleAddNewParam roleAddNewParam) {
        log.debug("开始执行【新增角色数据】的业务");
        checkName(null,roleAddNewParam.getName());
        Role role = new Role();
        BeanUtils.copyProperties(roleAddNewParam, role);
        role.setCreated(LocalDateTime.now());
        role.setUpdated(LocalDateTime.now());
        int insertCount = roleMapper.insert(role);
        if (insertCount != 1) {
            String message = "添加角色失败";
            log.warn(message);
            throw new ServiceException(ERR_INSERT, message);
        }
        addNewRolePermission(role.getId(), roleAddNewParam.getPermissionIds());
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除角色数据】的业务");
        checkId(id);
        int deleteCount = roleMapper.deleteById(id);
        if (deleteCount != 1) {
            String message = "删除角色失败";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }
        deleteRolePermissionById(id);
        deleteAdminRoleById(id);

    }

    @Override
    public void update(RoleUpdateParam roleUpdateParam) {
        log.debug("开始处理【修改角色数据】的业务");
        checkId(roleUpdateParam.getId());
        checkName(roleUpdateParam.getId(), roleUpdateParam.getName());
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateParam, role);
        role.setUpdated(LocalDateTime.now());
        roleMapper.updateById(role);
        rolePermissionMapper.deleteByRoleId(roleUpdateParam.getId());
        addNewRolePermission(role.getId(), roleUpdateParam.getPermissionIds());
        log.debug("已完成【修改角色数据】的业务");
    }

    @Override
    public List<RoleListItemVO> list() {
        log.debug("开始处理【查询角色列表】的业务，无参数");
        return roleMapper.list();
    }

    private void checkId(Long id) {
        QueryWrapper<Role> queryAdminName = new QueryWrapper<>();
        queryAdminName.eq("id", id);
        int countByName = roleMapper.selectCount(queryAdminName);
        if (countByName == 0) {
            String message = "角色id不存在";
            log.warn(message);
            throw new ServiceException(NOT_FOUND, message);
        }
    }

    private void checkName(Long id,String name) {
        QueryWrapper<Role> queryAdminName = new QueryWrapper<>();
        queryAdminName.eq("name", name).ne("id",id);
        int countByName = roleMapper.selectCount(queryAdminName);
        if (countByName > 0) {
            String message = "管理员名称被占用";
            log.warn(message);
            throw new ServiceException(CONFLICT, message);
        }
    }//检查name占用情况

    private void deleteRolePermissionById(Long id) {
        int deleteCount = rolePermissionMapper.deleteByRoleId(id);
        if (deleteCount < 1) {
            String message = "未能成功删除角色权限";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }
    }

    private void addNewRolePermission(Long id, Long[] permissionIds) {
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(id);
            rolePermission.setPermissionId(permissionId);
            rolePermission.setCreated(LocalDateTime.now());
            rolePermission.setUpdated(LocalDateTime.now());
            int addNewCount = rolePermissionMapper.insert(rolePermission);
            if (addNewCount != 1) {
                String message = "添加角色权限失败";
                log.warn(message);
                throw new ServiceException(ERR_INSERT, message);
            }
        }
    }

    private void deleteAdminRoleById(Long id) {
        String countAdminIdByRoleId = adminRoleMapper.countAdminIdByRoleId(id);
        if (countAdminIdByRoleId != null) {
            String message = "以下管理员："+countAdminIdByRoleId+"拥有该角色，请先删除或修改相关管理员";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }
    }
}
